# koroFileHeader at Home PC
# Create: 2022-10-29 10:16:41
# LastEdit: 2022-11-13 16:17:02
"""Home页面 系列视图"""
__author__ = '749B'

import json

from datetime import timedelta
from django.db.models import Sum
from django.shortcuts import render

from pyecharts.charts import Pie
from pyecharts import options as opts

from utils.cache import cache_auto_key

from .. import models
from .restapi import JsonResponse

import logging
logger = logging.getLogger(__name__)
logger.success = lambda msg, *args, **kwargs: logger.log(25, msg, *args, **kwargs)  # type: ignore


# Create your views here.
def home(request):
    return render(
        request, 
        "billing/home.html", 
        )

def panel_last_summary(request):
    summary = models.Summary.objects.latest('report_generation_date')
    pnl = {
        'alternative': 'panel-primary' if summary.ending_balance > 0 else 'panel-danger',
        'title': 'h3',
        'heading': f'账单月：{summary.report_month:%Y-%m}',
        'list': [],
        }
    pnl['list'].append(f'当前余额：{summary.ending_balance:,.2f}')
    pnl['list'].append(f'当月消费：{summary.total_usage:,.2f}')
    pnl['list'].append(f'报告日期：{summary.report_generation_date}')
    return render(
        request, 
        'bootstrap/panel.html',
        {'pnl': pnl},
        )

def panel_account(request):
    account = models.Account.objects.first()
    assert account
    pnl = {
        'alternative': 'panel-info',
        'title': 'h3',
        'heading': '合约信息',
        'list': [],
        }
    pnl['list'].append(f'合约编号：{account.enrollment}')
    pnl['list'].append(f'公司名称：{account.name}')
    pnl['list'].append('密钥信息：辅助密钥')
    return render(
        request, 
        'bootstrap/panel.html',
        {'pnl': pnl},
        )


def start_and_end_date():
    """开始和结束的日期
    如果当月记录已有10天则查看当月的数据
    如果不足10天则查看最近30天的数据
    """
    last_date = models.Detail.objects.latest('date').date
    assert last_date, '确保last_date不是None'
    if last_date.day >= 10:
        start_date = last_date.replace(day=1)
    else:
        start_date = last_date - timedelta(days=30)
    return start_date, last_date

@cache_auto_key(cache_key='nohash')
def pie_service_cache(start_date):
    logger.debug('调用缓存: home.pie_service_cache(%s)', start_date)
    qs = (
        models.Detail.objects
        .filter(date__gte=start_date)
        .values('consumed_service')
        .annotate(cost=Sum('extended_cost'))
        .filter(cost__gt=0)
        .order_by('-cost')
        )
    return qs

def panel_top_service(request):
    start_date, end_date = start_and_end_date()
    qs = pie_service_cache(start_date)
    pnl = {
        'alternative': 'panel-info',
        'heading': 'Service Top 10',
        'body': [f'{start_date} ~ {end_date}'],
        'table': {'head': ['Service', 'Cost'], 'body': []},
        }
    if start_date.day != 1:
        cost_sum = qs.aggregate(Sum('cost'))['cost__sum']
        pnl['body'].append(f"费用总计：{cost_sum:,.2f}")
    for q in qs[:10]:
        pnl['table']['body'].append([q['consumed_service'] or 'No Name', format(q['cost'], ',.2f')])
    return render(
        request, 
        'bootstrap/panel.html',
        {'pnl': pnl},
        )
    
def pie_service(request):
    start_date, _ = start_and_end_date()
    qs = pie_service_cache(start_date)
    pie = Pie()
    pie.add(
        '', 
        [(
            i['consumed_service'].replace('Microsoft.', '').replace('microsoft.', '') or 'No Name',
            format(i['cost'], '.2f')
        ) for i in qs ],
        radius=["40%", "75%"],  # 空心圆环
        )
    pie.set_global_opts(legend_opts=opts.LegendOpts(is_show=False))
    pie.set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {d}%"),
        tooltip_opts=opts.TooltipOpts(formatter="{b}: {c}"),
        )
    c = pie.dump_options_with_quotes()
    return JsonResponse(json.loads(c))


@cache_auto_key(cache_key='nohash')
def pie_subscription_cache(start_date):
    logger.debug('调用缓存: home.pie_subscription_cache(%s)', start_date)
    qs = (
        models.Detail.objects
        .filter(date__gte=start_date)
        .values('subscription', 'subscription__name')
        .annotate(cost=Sum('extended_cost'))
        .filter(cost__gt=0)
        .order_by('-cost')
        )
    return qs

def panel_top_subscription(request):
    start_date, end_date = start_and_end_date()
    qs = pie_subscription_cache(start_date)
    pnl = {
        'alternative': 'panel-info',
        'heading': 'Subscription Top 10',
        'body': [f'{start_date} ~ {end_date}', f'活跃订阅：{qs.count()}'],
        'table': {'head': ['Subscription', 'Cost'], 'body': []},
        }
    for q in qs[:10]:
        pnl['table']['body'].append([q['subscription__name'], format(q['cost'], ',.2f')])
    return render(
        request, 
        'bootstrap/panel.html',
        {'pnl': pnl},
        )

def pie_subscription(request):
    start_date, _ = start_and_end_date()
    qs = pie_subscription_cache(start_date)
    pie = Pie()
    pie.add(
        '', 
        [(
            i['subscription__name'],
            format(i['cost'], '.2f')
        ) for i in qs ],
        radius=["40%", "75%"],  # 空心圆环
        )
    pie.set_global_opts(legend_opts=opts.LegendOpts(is_show=False))
    pie.set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {d}%"),
        tooltip_opts=opts.TooltipOpts(formatter="{b}: {c}"),
        )
    c = pie.dump_options_with_quotes()
    return JsonResponse(json.loads(c))


    